package hlhj.com.carviewpad.presenters

import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Environment
import android.widget.Toast
import com.amap.api.location.AMapLocation
import com.amap.api.track.AMapTrackClient
import com.amap.api.track.ErrorCode
import com.amap.api.track.OnTrackLifecycleListener
import com.amap.api.track.TrackParam
import com.amap.api.track.query.model.*
import com.example.mymvp.log
import com.example.mymvp.mvp.BasePresenter
import com.tbruyelle.rxpermissions.RxPermissions
import hlhj.com.carviewpad.Constant
import hlhj.com.carviewpad.Iviews.MainVIew
import hlhj.com.carviewpad.modules.MainModule
import com.amap.api.track.query.model.DistanceRequest
import hlhj.com.carviewpad.utils.FileUtil
import java.io.File
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationListener
import hlhj.com.carviewpad.javabean.*
import hlhj.com.carviewpad.service.UploadService
import hlhj.com.carviewpad.utils.SPHelper


/**
 * Created by Never Fear   on 2018\12\28 0028.
Never More....
 */
class MainPresenter :BasePresenter<MainModule,MainVIew>(), MainVIew {
    override fun setGame(gameBean: GameBean) {
        view?.setGame(gameBean)
    }
    override fun setNotce(myBaseBean: MyBaseBean) {
        view?.setNotce(myBaseBean)
    }

    override fun setIsUpdata(myBaseBean: MyBaseBean) {
        view?.setIsUpdata(myBaseBean)
    }

    override fun setAdvs(advs: ArrayList<AdvBean>) {
        view?.setAdvs(advs)
    }

    override fun setIds(idBean: IdBean) {
        view?.setIds(idBean)
    }

    override fun setFilesBean(filesBean: FilesBean) {
        view?.setFilesBean(filesBean)
    }
    //获取公告
    fun getNotce(c:Context){
        module?.getNotce(c)
    }
    fun getGame(c:Context){
        module?.getGame(c)
    }
    fun getIsUpdata(c:Context){
        module?.getisUpdata(c)
    }
    private var trackerClient:AMapTrackClient?=null
    private var trackerLifelistener:OnTrackLifecycleListener?=null

    private var tmid:Long=0

    //获取设备信息
    fun getDeviceInfo(device_sn:String,c:Context){
        module?.getEquipmentInfo(device_sn,c)
    }
    //获取文件
    fun getFiles(c:Context){
        module?.getFiles(c)
    }
    override fun createModule() {
        module=MainModule()
        module.lis=this
    }
    //权限检测
    fun checkPermission(c:Context){
        val b = RxPermissions.getInstance(c).isGranted(Manifest.permission.ACCESS_COARSE_LOCATION)
                && RxPermissions.getInstance(c).isGranted(Manifest.permission.ACCESS_FINE_LOCATION)
        &&RxPermissions.getInstance(c).isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if (!b){
            RxPermissions.getInstance(c).request(Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe {
                        b->
                    }
        }
    }
    //遍历文件
    fun listAdvs(c:Context){
        val gamed = Environment.getExternalStorageDirectory()
        val gampath = gamed.absolutePath + "/game"
        val gamfile = File(gampath)
        if (!gamfile.exists()){
            gamfile?.mkdirs()
        }

        val directory = Environment.getExternalStorageDirectory()
        val dirPath = directory.absolutePath + "/carpad"
        val file = File(dirPath)
        if (!file.exists()){
            file?.mkdirs()
        }
        val advs = FileUtil.getFileName(dirPath,c)
        advs?.let {
            setAdvs(it)
        }

        val coverPath = Environment.getExternalStorageDirectory()
        val cPath = coverPath.absolutePath + "/carpad/cover"
        val cFile = File(cPath)
        if (!cFile.exists()){
            cFile?.mkdirs()
        }

        val elements = FileUtil.getCovers(cPath)
        elements?.let {
            Constant.coverList.addAll(it)
        }

        Constant.coverList.forEachIndexed { index, s ->
        }
    }
    //初始化采集器
    fun initTracker(c:Context){
        trackerClient = AMapTrackClient(c.applicationContext)
        trackerClient?.setInterval(5,30)

        trackerLifelistener = object : OnTrackLifecycleListener {
            override fun onStartGatherCallback(p0: Int, p1: String?) {
                if (p0 == ErrorCode.TrackListen.START_GATHER_SUCEE
                        || p0 == ErrorCode.TrackListen.START_GATHER_ALREADY_STARTED) {
                    Toast.makeText(c, "开始采集", Toast.LENGTH_SHORT).show()
                    log("fhp","------开始采集")
                }else{
                    log("fhp","------采集失败")

                }
            }

            override fun onStopTrackCallback(p0: Int, p1: String?) {

            }

            override fun onBindServiceCallback(p0: Int, p1: String?) {

            }

            override fun onStopGatherCallback(p0: Int, p1: String?) {

            }

            override fun onStartTrackCallback(p0: Int, p1: String?) {
                if (p0 == ErrorCode.TrackListen.START_TRACK_SUCEE
                        || p0 == ErrorCode.TrackListen.START_TRACK_ALREADY_STARTED) {
                    Toast.makeText(c, "开始上报", Toast.LENGTH_SHORT).show()
                    log("fhp","------开始上报")
                }
            }
        }
        trackerClient?.setOnTrackListener(trackerLifelistener)
    }
    //开始上报
    fun startTracer(c:Context){
        trackerClient?.queryTerminal(QueryTerminalRequest(Constant.sid.toLong(),Constant.testName),object :OnTrackListener{
            override fun onLatestPointCallback(p0: LatestPointResponse?) {
            }

            override fun onCreateTerminalCallback(p0: AddTerminalResponse?) {
            }

            override fun onQueryTrackCallback(p0: QueryTrackResponse?) {
            }

            override fun onDistanceCallback(p0: DistanceResponse?) {
            }

            override fun onQueryTerminalCallback(p0: QueryTerminalResponse?) {
                if (p0!!.isSuccess){//请求成功
                    if (p0!!.tid<=0){//终端不存在，先创建
                        trackerClient?.addTerminal(AddTerminalRequest(Constant.testName,Constant.sid.toLong()),
                                object :OnTrackListener{
                            override fun onLatestPointCallback(p0: LatestPointResponse?) {
                            }
                            override fun onCreateTerminalCallback(p0: AddTerminalResponse?) {
                                if (p0!!.isSuccess){
                                    //创建成功，开启Tracker
                                    val tid = p0.tid
                                    tmid=tid
                                    Constant.tid=tid
                                    log("fhp","-------------0终端ID为${tid}")
                                    trackerClient?.startTrack(TrackParam(Constant.sid.toLong(),tid),trackerLifelistener)
                                }else{
                                    Toast.makeText(c,"创建失败",Toast.LENGTH_SHORT).show()
                                }
                            }
                            override fun onQueryTrackCallback(p0: QueryTrackResponse?) {
                            }
                            override fun onDistanceCallback(p0: DistanceResponse?) {
                            }
                            override fun onQueryTerminalCallback(p0: QueryTerminalResponse?) {
                            }
                            override fun onHistoryTrackCallback(p0: HistoryTrackResponse?) {
                            }
                            override fun onParamErrorCallback(p0: ParamErrorResponse?) {
                            }
                            override fun onAddTrackCallback(p0: AddTrackResponse?) {
                            }
                        })
                    }else{//已存在此终端，直接开启Tracker
                        val tid = p0.tid
                        log("fhp","-------------1终端ID为${tid}")
                        tmid=tid
                        Constant.tid=p0.tid
                        trackerClient?.startTrack(TrackParam(Constant.sid.toLong(),tid),trackerLifelistener)
                    }
                }else{
                    log("fhp","错误信息${p0.errorMsg}--${p0.errorCode}--${p0.errorDetail}---${Constant.sid.toLong()}")
                    Toast.makeText(c,"请求失败",Toast.LENGTH_SHORT).show()
                }
            }

            override fun onHistoryTrackCallback(p0: HistoryTrackResponse?) {
            }

            override fun onParamErrorCallback(p0: ParamErrorResponse?) {
            }

            override fun onAddTrackCallback(p0: AddTrackResponse?) {
            }
        })
    }
    companion object {
        //上一次的位置

        //获取里程
        fun getMillter(c:Context,onBack:OnBack){
            val curr = System.currentTimeMillis()
            val distanceRequest = DistanceRequest(
                    Constant.sid.toLong(),
                    Constant.tid,
                    curr - 12 * 60 * 60 * 1000, // 开始时间
                    curr, // 结束时间
                    -1  // 轨迹id，传-1表示包含散点在内的所有轨迹点
            )
            val trackClient = AMapTrackClient(c.applicationContext)
            trackClient?.queryDistance(distanceRequest,object :OnTrackListener{
                override fun onLatestPointCallback(p0: LatestPointResponse?) {
                }

                override fun onCreateTerminalCallback(p0: AddTerminalResponse?) {
                }

                override fun onQueryTrackCallback(p0: QueryTrackResponse?) {
                }

                override fun onDistanceCallback(p0: DistanceResponse?) {
                    if (p0!!.isSuccess){
                        onBack.backStr(p0.distance.toString())
                        log("fhp","里程获取成功${p0.distance}")
                    }else{
                        log("fhp","里程获取失败${p0.errorCode}--${p0.errorDetail}")
                    }
                }

                override fun onQueryTerminalCallback(p0: QueryTerminalResponse?) {
                }

                override fun onHistoryTrackCallback(p0: HistoryTrackResponse?) {
                }

                override fun onParamErrorCallback(p0: ParamErrorResponse?) {
                }

                override fun onAddTrackCallback(p0: AddTrackResponse?) {
                }
            })


        }
    }
    interface OnBack{
        fun backStr(str:String)
    }
    //开启上传服务
    fun startUpload(c:Context){
        val intent = Intent(c, UploadService::class.java)
        c.startService(intent)
    }
    /*定位*/
    //声明AMapLocationClientOption对象
    var mLocationOption: AMapLocationClientOption? = null
    //声明AMapLocationClient类对象
    var mLocationClient: AMapLocationClient? = null
    fun initLocation(c:Context){
        mLocationClient= AMapLocationClient(c)
        mLocationOption= AMapLocationClientOption()
        mLocationClient?.setLocationListener {
            aMapLocation ->
            if (!SPHelper.getLocation(c).equals(aMapLocation.district)){
                listAdvs(c)
            }
            SPHelper.saveLocation(c,aMapLocation.district)
        }
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption?.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption?.setInterval(3000);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption?.setHttpTimeOut(20000);
        //给定位客户端对象设置定位参数
        mLocationClient?.setLocationOption(mLocationOption);
//启动定位
        log("定位","开始定位")
        mLocationClient?.startLocation();
    }
}